package com.bruce.starts.demo.thread.cyclicBarrier;

import java.util.Vector;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class OrderDemo<P,D> {
    // 订单队列
    private Vector<P> pos = new Vector<>();
    //派单队列
    private Vector<D> dos = new Vector<>();
    Executor executor = Executors.newFixedThreadPool(1);
    Runnable barrierAction;
    final CyclicBarrier barrier  = new CyclicBarrier(2, ()->{
        executor.execute(()->check());
    });

    public void check(){
        P p = pos.remove(0);
        D d = dos.remove(0);
        System.out.println("开始比较："+p.toString()+":"+d.toString());
    }

    public void exec(P p,D d){
        AtomicInteger atomicInteger = new AtomicInteger(4);
        Thread t1 = new Thread(()->{
            while (atomicInteger.get()>=0){
                System.out.println("订单："+p.toString()+ThreadLocalRandom.current().nextInt(100));
                pos.add(p);
                try {
                    barrier.await();
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(()->{
            while (atomicInteger.get()>=0){
                System.out.println("派单："+d.toString()+ThreadLocalRandom.current().nextInt(100));
                dos.add(d);
                try {
                    barrier.await();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }

    public static void main(String[] args) {
        OrderDemo<String,String> orderDemo = new OrderDemo<>();
        String t1 = "test";
        orderDemo.exec(t1,t1);
    }
}
